package com.hsyt.pms.support.common;

import com.alibaba.fastjson.JSONObject;
import com.hsyt.pfc.support.util.LoggerUtil;
import com.hsyt.pms.api.common.DictionaryVo;
import com.hsyt.pms.api.common.PmsEnumValue;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description:
 * @ClassName: RedisCacheHandler
 * @Package: com.hsyt.pfc.redis
 * @Author: wangze@hsyuntai.com
 * @Date: 2018年9月28日 10:26
 * @Copyright: 版权归 HSYUNTAI 所有
 */
@Slf4j
@Component
public class EnumHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(EnumHandler.class);

    private static StringRedisTemplate stringRedisTemplate;

    private static ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Resource
    public void setThreadPoolTaskExecutor(ThreadPoolTaskExecutor threadPoolTaskExecutor) {
        if (null == threadPoolTaskExecutor) {
            throw new IllegalArgumentException("threadPoolTaskExecutor not null");
        }
        EnumHandler.threadPoolTaskExecutor = threadPoolTaskExecutor;
    }

    @Resource
    public void setStringRedisTemplate(StringRedisTemplate stringRedisTemplate) {
        if (null == stringRedisTemplate) {
            throw new IllegalArgumentException("stringRedisTemplate not null");
        }
        EnumHandler.stringRedisTemplate = stringRedisTemplate;
    }

    /**
     * @param enumType
     * @Description 获取指定枚举类型key-value集合
     * @MethodName getEnumDict
     * @Return java.util.Map
     * @Throw
     */
    public static Map<String, String> getEnumDict(String enumType) {
        try {
            Map<Object, Object> resultMap = null;
            try {
                resultMap = stringRedisTemplate.opsForHash().entries("CFG_ENUM_DICT" + enumType);
            } catch (Exception e) {
                LoggerUtil.error(LOGGER, "redis获取{0}枚举类型失败:{1}", enumType, e);
            }
            if (null == resultMap) {
                List<PmsEnumValue> enumValues = null;
                if (CollectionUtils.isEmpty(enumValues)) {
                    return new HashMap<>();
                }
                try {
                    //异步缓存
                    threadPoolTaskExecutor.execute(() -> {
                        EnumCacheHelper.syncEnumDict(enumValues);
                    });
                } catch (Exception e) {
                    LoggerUtil.error(LOGGER, "异步缓存数据失败：{0}，{1}", JSONObject.toJSON(enumValues), e);
                }
                return enumValues.stream().collect(
                        Collectors.toMap(PmsEnumValue::getEnumValue, PmsEnumValue::getEnumTxt, (key1, key2) -> key1));
            }
            return resultMap.entrySet().stream().collect(Collectors.toMap(value -> value.getKey().toString(),
                    value -> value.getValue().toString()));
        } catch (Exception e) {
            LoggerUtil.error(LOGGER, "获取{0}枚举类型失败:{1}", enumType, e);
            return new HashMap<>();
        }
    }

    /**
     * @param group
     * @param dictCode
     * @Description 获取指定数据字段的值
     * @MethodName getSysDictionaryValue
     * @Return java.lang.String
     * @Throw
     */
    public static Map<String, String> getSysDictionaryValue(String group, String dictCode) {
        try {
            String result = null;
            try {
                result = (String) stringRedisTemplate.opsForHash().get("CFG_SYS_DICT" + group, dictCode);
            } catch (Exception e) {
                LoggerUtil.error(LOGGER, "redis获取{0}分组{1}数据字典失败:{2}", group, dictCode, e);
            }
            if (StringUtils.isBlank(result)) {
                DictionaryVo dict = null;
                if (null == dict) {
                    return new HashMap<>();
                }
                try {
                    //异步缓存
                    threadPoolTaskExecutor.execute(() -> {
                        EnumCacheHelper.syncDictionary(Arrays.asList(dict));
                    });
                } catch (Exception e) {
                    LoggerUtil.error(LOGGER, "异步缓存数据失败：{0}，{1}", JSONObject.toJSON(dict), e);
                }
                return new HashMap() {{
                    put("name", dict.getDictName());
                    put("ext", dict.getExtValue());
                }};
            }
            return JSONObject.parseObject(result, Map.class);
        } catch (Exception e) {
            LoggerUtil.error(LOGGER, "获取{0}分组{1}数据字典失败:{2}", group, dictCode, e);
            return null;
        }
    }


}
